package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 06月 14日
 * Time: 下午6:01
 *
 * @QQ : 1234567890
 * **********************************
 */
public class NameCardMessage extends CcMsgStructure {

    private Message mmCallback;
    private Context mContext;

    public NameCardMessage(Message callback,Context mContext) {
        this.mmCallback = callback;
        this.mContext = mContext;
    }

    @Override
    public void onReceive(JSONObject data) {
        ArrayList<String> cardData = new ArrayList<String>();
        try {
            JSONObject obj = data.getJSONObject("data");
            cardData.add(obj.getString("name"));
            cardData.add(obj.getString("phone"));
            // 判断第二个号码，不需要了
            if (obj.has("landline")) {
                cardData.add(obj.getString("landline"));
            } else {
                cardData.add("");
            }
            cardData.add(obj.getString("company"));
            cardData.add(obj.getString("job"));
            cardData.add(obj.getString("email"));
            cardData.add(obj.getString("address"));
            cardData.add(obj.getString("avatar"));
            cardData.add(obj.getString("sex"));
            PreferenceUtil.getInstance(mContext).saveCloudContact(Constants.CONTACT_NAME_CARD, cardData);
            PreferenceUtil.getInstance(mContext).save(PreferenceUtil.NAMECARD_AVATAR, obj.getString("avatar"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (mmCallback != null) {
            mmCallback.arg1 = 0;
            mmCallback.obj = cardData;
            mmCallback.sendToTarget();
        }

    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
